﻿using System;
using System.Collections.Generic;
using kk.components.contracts;
using kk.messages.contracts.DataModel;
using kk.preiskategorieadapter.filereader;

namespace kk.preiskategorieadapter
{
    public class PreiskategorieAdapter : IPreiskategorieAdapter
    {
        private const string FILENAME = "preisschema.txt";
        private IReadFile readFile;

        public PreiskategorieAdapter()
        {
            readFile = new ReadFile();
        }

        public PreiskategorieAdapter(IReadFile readfile)
        {
            this.readFile = readfile;
        }


        internal string[] SplitLine(string line)
        {
            string[] fields;
            if (string.IsNullOrEmpty(line)) return new string[0];

            fields = line.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
            if (fields.Length != 2) throw new ArgumentException("Zeilenaufbau ist: A=9,50"); 
            return fields;
        }

        internal Preiskategorie GetPreisKategorie(string[] pair)
        {
            return new Preiskategorie(Convert.ToChar(pair[0]), Convert.ToDouble(pair[1]));
        }

        internal IEnumerable<Preiskategorie> GetPreisKategorien()
        {
            foreach (var line in GetLines())
            {
                yield return GetPreisKategorie(SplitLine(line));
            }
        }

        public void ProcessPreiskategorien(Request<IEnumerable<Preiskategorie>> request)
        {
            //IEnumerable<Preiskategorie> preiskats = new[] {new Preiskategorie('A', 10.0), new Preiskategorie('B', 9.5), 
            //    new Preiskategorie('C', 8.0) };
            request.ResponsePin(GetPreisKategorien());
        }
  
        internal string[] GetLines()
        {
            readFile = new ReadFile();
            string[] lines = new string[] { };
            Action<string[]> action = new Action<string[]>(
                delegate(string[] texts)
                {
                    lines = texts;
                }
                );
            Request<string, string[]> request = new Request<string, string[]>(FILENAME, action);
            readFile.ProcessKategorieadpaterReadFile(request);

            return lines;
        }
    }
}
